<?php

            // +----------------------------------------------------------------------
            // | 
            // +----------------------------------------------------------------------
            // | Copyright (c) 2016~2030 http://www.jmzh1688.com All rights reserved.
            // +----------------------------------------------------------------------
            // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
            // +----------------------------------------------------------------------
            // | Author: lxl
            // +----------------------------------------------------------------------
            
            
            namespace app\jmzhfs\controller;
            
            use think\Controller;
            use think\Db;
            
            
            
            class Upload extends  Controller
            {


                public $localapppath="/www/wwwroot/oa.jmzh5178.com/application/";
                public $autohtmltag="jmzhfsauto";
                public $noautohtmltag="*jmzhfsauto*";
                public $uploadkey="afarsfxfaafrrr";
            
            
                public function uploadproject()
                {
                    $extlist='png,jpg,gif,jpeg,doc,docx,xls,xlsx,pdf,zip,cert,txt,pem';
                    if (request()->isPost()) {
            
                        $para = input("post.");

                        if($para["uploadkey"]!=$this->uploadkey)
                        {
                            return -999;                            
                        }

                        if($para["type"]=="tablejson")
                        {
                           $result= $this->uploadtablejson();
                            return  $result;
                        }
            
                        if($para["type"]=="appfile")
                        {
                            $result= $this->uploadappfile();
                            return  $result;
                        }
            
                     
                    }
                    return -15;
            
                }
            
            
            
                private function uploadtablejson()
                {
                    $para = input("post.");
                    $content=$para["content"];
                   $result= $this->syncfield($content);

                   return 1;

                }


                private function uploadappfile() //application
                {
                    $para = input("post.");
                    $file = request()->file('file');


                    $filename = $para["filename"];
                    $issafe = $para["issafe"];
                    $filenameorg = $para["filenameorg"];
                    
                    $fpath=$this->localapppath;
                    $apppath=ROOT_PATH."application/".$filename ;
                    $apppath=str_replace("\\","/",$apppath);
                    $apppath=str_replace("//","/",$apppath);

               
                    $newpath=dirname($apppath);


                    //jmzhfsauto

                    $txt=$this->readhtmlfile($apppath);//
                    if($txt!=""&& $issafe!="0")
                    {
                        if(strpos($txt,$this->noautohtmltag)>1)
                        {
                            return -3;
                        }
    
                        if(strpos($txt,$this->autohtmltag) === false)
                        {
                         return -4;
                        }

                    }
          
                   
                    $this->myCreateDir($newpath);
                    $info = $file->move($newpath, '');

                    if ($info) {
                        $src =  '/jmzhfs/' . $info->getFilename();
                        return 1;
                    } else {
                        return -5;
                    }

                }

                function myCreateDir($path)
                {
                    if (is_dir($path)){  
                        return true;
                    }else{
                        $res=mkdir($path,0777,true); 
                        if ($res){
                            return true;
                        }else{
                            return false;
                        }
                    }
                    return false;
                }
function readhtmlfile($jsonfile)
{
    if(file_exists($jsonfile))
    {
        $json_string = file_get_contents($jsonfile);  
       
        return $json_string;

    }
    else
    {
        return "";
    }

}
                public function getvalueFromArray($key,$arr)
                {
            
                    if (array_key_exists($key, $arr) ) {
                       return $arr[$key];
                    }
                    return "";
                }
                
    private function syncfield($contentjson)
    {

        $data = json_decode($contentjson, true);
     


        $tablename=  config('database.prefix').$this->getvalueFromArray("tablename",$data);
        $sql="select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_SCHEMA='".$this->getvalueFromArray("dbname",$data)."' and"
        ."( TABLE_NAME='".$tablename."' or TABLE_NAME like '%table=".$tablename."&%') ";
        $t=Db::name('jmzhfs_sys_user');
        $res = $t->query($sql); 
        if(count($res)==0)
        {
            $sqltable="CREATE TABLE ".$tablename."\n(\n";
            for($p=0;$p<count($data['list']);$p++)
            {
                if($data['list'][$p]["type"]=="id") 
                {
                    $sqltable=$sqltable.$data['list'][$p]["name"]." int auto_increment primary key";
                }
                else {
                
                    $sqltable=$sqltable.$data['list'][$p]["name"]."  ".$data['list'][$p]["type"]."";
                }
                if($p<count($data['list'])-1)
                {
                    $sqltable=$sqltable.",\n";
                }
            }
            $sqltable=$sqltable."\n)\n";
            $res = $t->query($sqltable); 
            
        }
        else
        {
            $sql=" select COLUMN_NAME,COLUMN_TYPE from information_schema.COLUMNS where
             table_schema='".$this->getvalueFromArray("dbname",$data)."' and "
             ."( TABLE_NAME='".$tablename."' or TABLE_NAME like '%table=".$tablename."&%' )";
            $arrcolumnresult = $t->query($sql); 
            $arrcolumn=[];
            for($p=0;$p<count($arrcolumnresult);$p++)
            {
                $arrnow['COLUMN_NAME']=$arrcolumnresult[$p]['COLUMN_NAME'];
                $arrnow['COLUMN_TYPE']=$arrcolumnresult[$p]['COLUMN_TYPE'];




                if(strpos($arrnow['COLUMN_NAME'],';field=')>1)
                {
                    //&amp;field=id&
                    $nowstr= $arrnow['COLUMN_NAME'];
                    $pattern_1 = '/;field=(.*?)&/';
                    $num = preg_match($pattern_1,$nowstr, $matches_1,PREG_OFFSET_CAPTURE,8);
                    $fieldname=$matches_1;
                    $arrnow['COLUMN_NAME']=$fieldname;

                }
                
                $arrcolumn[]=$arrnow;
            }

            
            $sqltable="";
            for ($p=0;$p<count($data['list']);$p++) {

                if($data['list'][$p]["name"]=="id"){ continue;}
                
                $found_key = array_search($data['list'][$p]["name"], array_column($arrcolumn, 'COLUMN_NAME'));
                if($found_key==false&&$data['list'][$p]["name"]!="id"){

                    $sqltable="ALTER table ".$tablename."  ADD ".$data['list'][$p]["name"]."  ".$data['list'][$p]["type"].";\n";
                    $res = $t->query($sqltable); 
                }
                else
                {
                    if(strtolower($data['list'][$p]["type"])!= strtolower($arrcolumn[$found_key]["COLUMN_TYPE"]) )     
                    {
                        $sqltable="ALTER table ".$tablename."  modify  column ".$data['list'][$p]["name"]."  ".$data['list'][$p]["type"].";\n";
                        $res = $t->query($sqltable); 
                      
                    }               

                }

               

            }

         


        }

        return true;
       

    }
                
            }
            